import React from 'react';
import { connect } from 'react-redux';
import { Form, Icon, Input, Button, Row, Col, message, Tooltip } from 'antd';
import Particles from 'particlesjs';
import * as loginAction from '../../actions/login';
import './style.less';

function hasErrors(fieldsError) {
    return Object.keys(fieldsError).some(field => fieldsError[field]);
}

class LoginForm extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            isLogin: false,
            getCaptcha: null,
        }
    }
    componentDidMount() {
        this.getCaptcha();
        // 默认登陆按钮禁用
        // eslint-disable-next-line
        this.props.form.validateFields();
        // 开启粒子效果
        this.particles = Particles.init({
            selector: '.login-background',
            connectParticles: true,
            sizeVariations: 15,
            color: `#d9d9d9`,
            speed: '0.2',
        });
    }
    componentWillUnmount() {
        this.particles.destroy();
    }
    // 验证码
    getCaptcha = () => {
        // eslint-disable-next-line
        this.props.dispatch(loginAction.getCaptcha(Date.now())).then((res) => {
            this.setState({
                getCaptcha: 'data:image/jpeg;base64,' + res.slice(1, -1),
            });
        });
    }
    handleSubmit = (e) => {
        e.preventDefault();
        // eslint-disable-next-line
        this.props.form.validateFields((err, values) => {
            if (err) {
                return message.error(`登陆检验失败，请重试`);
            }
            // eslint-disable-next-line
            this.props.dispatch(loginAction.login(values)).then(res => {
                this.setState({
                    isLogin: res.success && res.statusCode === 200 ? true : res.message
                });
            });
        });
    }
    render() {
        // eslint-disable-next-line
        const { getFieldDecorator, getFieldsError, getFieldError, isFieldTouched } = this.props.form;
        const accountError = isFieldTouched('account') && getFieldError('account'),
            passwordError = isFieldTouched('password') && getFieldError('password'),
            captchaError = isFieldTouched('captcha') && getFieldError('captcha');

        return (
            <div className="login-container">
                {/* 背景 */}
                <canvas className="login-background" />
                <Row
                    type="flex"
                    justify="space-between"
                    align="middle"
                >
                    <Col xs={20} sm={14} md={12} lg={8} xl={6} className="login-form">
                        <div className="form">
                            <div className="slogen">登录 RETTC，发现更多的技术转移机会</div>
                            <Form onSubmit={this.handleSubmit}>
                                <Form.Item validateStatus={accountError ? 'error' : ''} help={accountError || ''}>
                                    {
                                        getFieldDecorator('account', {
                                            rules: [{ required: true, whitespace: true, message: '请输入用户名/邮箱/手机号!' }],
                                        })(<Input size="large" prefix={<Icon type="user" style={{ fontSize: 13 }} />} placeholder="请输入用户名/邮箱/手机号" />)
                                    }
                                </Form.Item>
                                <Form.Item validateStatus={passwordError ? 'error' : ''} help={passwordError || ''}>
                                    {
                                        getFieldDecorator('password', {
                                            rules: [{ required: true, whitespace: true, message: '请输入密码!' }],
                                        })(<Input size="large" prefix={<Icon type="lock" style={{ fontSize: 13 }} />} type="password" placeholder="请输入密码" />)
                                    }
                                </Form.Item>
                                <Form.Item validateStatus={captchaError ? 'error' : ''} help={captchaError || ''} extra="点击图片刷新验证码">
                                    <Col span={12}>
                                        {
                                            getFieldDecorator('captcha', {
                                                rules: [{ required: true, whitespace: true, message: '请输入验证码!' }],
                                            })(<Input maxLength="4" autoComplete="off" size="large" prefix={<Icon type="barcode" style={{ fontSize: 13 }} />} placeholder="请输入验证码" />)
                                        }
                                    </Col>
                                    <Col span={10} offset={2} onClick={this.getCaptcha}>
                                        <Tooltip title="点击图片刷新">
                                            <div className="img-code-container">
                                                <img className="img-code" src={this.state.getCaptcha} alt="验证码" />
                                            </div>
                                        </Tooltip>
                                    </Col>
                                </Form.Item>
                                <Form.Item style={{ textAlign: `center` }}>
                                    <Button
                                        type="primary"
                                        htmlType="submit"
                                        disabled={hasErrors(getFieldsError())}
                                        size="large"
                                    >登陆</Button>
                                    {
                                        this.state.isLogin === true ?
                                            <div className="success-tip">
                                                您已经成功登录 rettc，正在跳转...
                                                <p style={{ width: 1, height: 1, overflow: 'hidden',  visibility: 'hidden' }}>
                                                    {
                                                        window.location.href = '/user?init=true'
                                                    }
                                                </p>
                                            </div> :
                                            <div className="error-tip">{this.state.isLogin}</div>
                                    }
                                </Form.Item>
                            </Form>
                        </div>
                        <div className="sign-switch">
                            没有账号？
                            <a href="/signup" onClick={event => {
                                event.preventDefault();
                                this.particles.destroy();
                                // eslint-disable-next-line
                                this.props.history.push('/signup');
                            }}>注册</a>
                            <span className="ant-divider" />
                            <a href="/help" onClick={event => {
                                event.preventDefault();
                                this.particles.destroy();
                                // eslint-disable-next-line
                                this.props.history.push('/help');
                            }}>帮助</a>
                        </div>
                    </Col>)
                </Row>
            </div>
        );
    }
}

const mapStateToProps = (state) => {
    const { metaData } = state.loginReducer;

    return {
        metaData
    }
}

export default connect(mapStateToProps)(Form.create()(LoginForm))